<template>
  <div class="form-wrapper">
    <el-form :model="registerForm" label-width="70px" class="form-content">
      <h1>注册页面</h1>
      <!-- 表单项 -->
      <el-form-item label="用户名">
        <el-input v-model="registerForm.username"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="registerForm.email"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="registerForm.password" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleRegister">注册</el-button>
      </el-form-item>
      <div class="switch-link">
        已有账号？
        <el-link type="primary" @click="goLogin">去登录</el-link>
      </div>
    </el-form>
  </div>
</template>
<script setup>
import { reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { registerUser } from '@/api/user';

const registerForm = reactive({
  username: '',
  email: '',
  password: '',
});

const router = useRouter();

const handleRegister = async () => {
  if (!registerForm.username || !registerForm.email || !registerForm.password) {
    ElMessage.warning('请填写所有信息！');
    return;
  }

  try {
    const response = await registerUser({
      username: registerForm.username,
      email: registerForm.email,
      passwordHash: registerForm.password,
    });
    ElMessage.success(response.data);
    // 注册成功跳转登录页
    await router.push('/login');
  } catch (error) {
    if (error.response) {
      ElMessage.error(error.response.data);
    } else {
      ElMessage.error('注册失败');
    }
  }
};

const goLogin = () => {
  router.push('/login');
};
</script>

<style>
.form-wrapper {
  height: 80vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.form-content {
  width: 360px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  padding: 30px 40px;
  border-radius: 8px;
  background: #fff;
}
.switch-link {
  margin-top: 10px;
  font-size: 14px;
  text-align: center;
}
</style>
